ExcelVBA之If then 您所在的位置:网站首页 vba if判断语句不能自动更新 ExcelVBA之If then

ExcelVBA之If then

#ExcelVBA之If then| 来源: 网络整理| 查看: 265

在VBA过程里面作决定的最简单的方法就是使用If…Then语句。假使你想要基于某个条件选择一个行动,那么你可以使用下述结构:

 If 条件Then     语句1     语句2     语句N End If

如何使用On Error GoTo标志语句来绕过循环错误:

Sub SimpleIfThen() Dim weeks As String On Error GoTo VeryEnd weeks = InputBox("How many weeks are in a year:", "Quiz") If weeks52 Then MsgBox "Try Again": SimpleIfThen If weeks=52 Then MsgBox "Congratulations!" VeryEnd: End Sub

 过程IfThenAnd使用了四个If…Then语句来评估两个变量price和units的内容。在If…Then关键字之间的运算符AND使得测试多于一个的条件成为可能。使用了AND运算符时,所有条件都必须为真,VB才会去执行关键字Then和End之间的语句。因为过程的运行依赖于工作表单元格里输入的数据,所以从Excel窗口来运行它比较方便。

Sub IfThenAnd() Dim price As Single Dim units As Integer Dim rebate As Single Const strmsg1 = "To get a rebate you must buy an additional " Const strmsg2 = "Price must equal $7.00" units = Range("B1").Value price = Range("B2").Value If price = 7 AND units >= 50 Then rebate = (price * units) * 0.1 Range("A4").Value = "The rebate is: $" & rebate End If If price = 7 AND units < 50 Then Range("A4").Value = strmsg1 & 50 - units & " unit(s)." End If If price 7 AND units >= 50 Then Range("A4").Value = strmsg2 End If If price 7 AND units < 50 Then Range("A4").Value = "You didn't meet the criteria." End If End Sub

总结:指令块和缩进,要使If程序块更容易阅读和理解,可以使用缩进。对比下面的代码书写:

If condition Then action1 End If If condition Then action End If

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有